﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using Ultimus.WFServer;

namespace H2.NET
{
    #region API接口类
    /// <summary>
    /// 
    /// </summary>
    public class TaskAPI
    {
        #region 变量 Private
        private string _taskId = "";
        private string _process;
        private int _incident;
        private string _DraftID;
        private string _step;
        private string _summary;
        private string _username;
        private string _userfullname;
        private DateTime _starttime = System.DateTime.Now;
        private string _assigned_to_username;
        private string _assigned_to_userfullname;
        private bool _is_allow_submit;
        private bool _is_initiate;
        private bool _is_begin_step;
        private bool _is_re_assigned;
        private bool _is_confered;
        private bool _loaded = false;
        private List<Variable> _list = new List<Variable>();
        private List<Variable> _list_send = new List<Variable>();
        #endregion

        #region 构造 TaskAPI(函数)
        /// <summary>
        /// 
        /// </summary>
        public TaskAPI()
        {
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="TaskID"></param>
        public TaskAPI(string TaskID)
        {
            _taskId = TaskID;
            Load();
        }
        #endregion

        #region 方法 Load(加载电子表格对应值)
        /// <summary>
        /// 
        /// </summary>
        public bool Load()
        {
            try
            {
                _loaded = false;
                string error = "";
                Task tskTemp = new Task();

                //根据 TaskID 去取得表单对应的 url 地址
                _loaded = tskTemp.InitializeFromTaskId(_taskId);

                //如果返回为 true 时
                if (_loaded)
                {
                    //系统变量
                    this._process = tskTemp.strProcessName;
                    this._incident = tskTemp.nIncidentNo;
                    this._DraftID = DraftID;
                    this._step = tskTemp.strStepName;
                    this._username = tskTemp.strUser;
                    this._userfullname = tskTemp.strUserFullName;
                    this._summary = tskTemp.strSummary;
                    this._assigned_to_username = tskTemp.strAssignedToUser;
                    this._assigned_to_userfullname = tskTemp.strAssignedToUserFullName;
                    this._is_begin_step = tskTemp.nStepType == StepTypes.STEP_TYPE_BEGIN;
                    this._is_initiate = _taskId.Substring(0, 1) == "S";
                    this._is_re_assigned = tskTemp.nTaskSubStatus == TaskSubStatuses.TASK_STATUS_ACTIVE_REASSIGNED;
                    this._is_confered = tskTemp.nTaskSubStatus == TaskSubStatuses.TASK_STATUS_ACTIVE_CONFERED;

                    try
                    {
                        this._starttime = _is_initiate ? System.DateTime.Now : DateTime.FromOADate(tskTemp.dStartTime);
                    }
                    catch (Exception)
                    { }
                    this._is_allow_submit = (tskTemp.nTaskStatus == TaskStatuses.TASK_STATUS_ACTIVE || tskTemp.nTaskStatus == TaskStatuses.TASK_STATUS_DELAYED) ? true : false;

                    Variable[] o_variable;
                    tskTemp.GetAllTaskVariables(out o_variable, out error);

                    //清空变更列表
                    _list.Clear();
                    _list_send.Clear();
                    for (int i = 0; i < o_variable.Length; i++)
                    {
                        _list.Add(o_variable[i]);
                    }
                }

                return _loaded;

            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool Load(string TaskID)
        {
            _taskId = TaskID;
            return Load();

        }

        public bool Load(string TaskID, string DraftID)
        {
            _taskId = TaskID;
            _DraftID = DraftID;
            return Load();

        }

        public void Clear()
        {
            _taskId = "";
            _process = "";
            _incident = -2;
            _step = "";
            _summary = "";
            _username = "";
            _userfullname = "";
            _assigned_to_username = "";
            _assigned_to_userfullname = "";
            _is_allow_submit = false;
            _is_initiate = false;
            _is_re_assigned = false;
            _is_confered = false;
            _is_begin_step = false;
            _loaded = false;
            _list.Clear();
            _list_send.Clear();
        }

        public bool SubmitApprove(string TaskID, Variable[] v, int nParamIncidentNo)
        {
            Task t = new Task();
            t.InitializeFromTaskId(TaskID);
            string strError;
            return t.Send(v, "", null, ref nParamIncidentNo, out strError);
        }

        public int StepStatus(string StepLabel)
        {
            int status = -1;

            try
            {
                Incident inc = new Incident();
                inc.LoadIncident(Process, Incident);
                inc.GetStepStatus(StepLabel, out status);
            }
            catch (Exception)
            {
            }

            return status;
        }
        #endregion

        #region 方法 Load(加载电子表格对应值)
        /// <summary>
        /// 
        /// </summary>
        public bool Load(string Process, string Incident, string Step, ref string AssignedToUser)
        {
            try
            {
                //bool Flg = _process == Process && _incident.ToString() == Incident && _step == Step;

                _loaded = false;
                string error = "";
                Task tskTemp = new Task();

                //加载任务
                TasklistFilter filters = new TasklistFilter();
                filters.strProcessNameFilter = Process;
                filters.nIncidentNo = Convert.ToInt32(Incident);
                filters.strStepLabelFilter = Step;

                if (!string.IsNullOrEmpty(AssignedToUser))
                {
                    filters.strArrUserName = new string[1] { AssignedToUser };
                }

                Tasklist list = new Tasklist();
                list.LoadFilteredTasks(filters);

                //如果返回为 true 时
                if (list.GetTasksCount() > 0)
                {
                    //系统变量
                    tskTemp = list.GetNextTask();
                    AssignedToUser = tskTemp.strAssignedToUser;
                    _loaded = true;
                    this._taskId = tskTemp.strTaskId;
                    this._process = tskTemp.strProcessName;
                    this._incident = tskTemp.nIncidentNo;
                    this._step = tskTemp.strStepName;
                    this._username = tskTemp.strUser;
                    this._userfullname = tskTemp.strUserFullName;
                    this._summary = tskTemp.strSummary;
                    this._assigned_to_username = tskTemp.strAssignedToUser;
                    this._assigned_to_userfullname = tskTemp.strAssignedToUserFullName;
                    this._is_begin_step = tskTemp.nStepType == StepTypes.STEP_TYPE_BEGIN;
                    this._is_initiate = _taskId.Substring(0, 1) == "S";
                    this._is_re_assigned = tskTemp.nTaskSubStatus == TaskSubStatuses.TASK_STATUS_ACTIVE_REASSIGNED;
                    this._is_confered = tskTemp.nTaskSubStatus == TaskSubStatuses.TASK_STATUS_ACTIVE_CONFERED;

                    try
                    {
                        this._starttime = _is_initiate ? System.DateTime.Now : DateTime.FromOADate(tskTemp.dStartTime);
                    }
                    catch (Exception)
                    { }
                    this._is_allow_submit = (tskTemp.nTaskStatus == TaskStatuses.TASK_STATUS_ACTIVE || tskTemp.nTaskStatus == TaskStatuses.TASK_STATUS_DELAYED) ? true : false;

                    Variable[] o_variable;
                    tskTemp.GetAllTaskVariables(out o_variable, out error);

                    //清空变更列表
                    _list.Clear();
                    _list_send.Clear();
                    for (int i = 0; i < o_variable.Length; i++)
                    {
                        _list.Add(o_variable[i]);
                    }

                    return _loaded;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }
        #endregion

        #region 方法 Send(提交表单步骤)
        /// <summary>
        /// 
        /// </summary>
        public bool Send()
        {
            try
            {
                int incident = -2;
                bool flg = false;
                string error = "";
                Task tskTemp = new Task();

                //根据 TaskID 加载任务
                flg = tskTemp.InitializeFromTaskId(_taskId);

                //如果当前任务存在的情况
                if (flg && (tskTemp.nTaskStatus == TaskStatuses.TASK_STATUS_ACTIVE || tskTemp.nTaskStatus == TaskStatuses.TASK_STATUS_DELAYED))
                {
                    //如果是"发起流程"的情况,调用 SendForm 方法; 否则,调用 Send 方法
                    if (IsInitiate)
                    {
                        //如果用户名为空,则抛出异常
                        if (string.IsNullOrEmpty(_username))
                        {
                            throw new Exception("发起流程的情况,用户名不得为空!");
                        }
                        Logging.GetLogger().Error(string.Format("Before tskTemp.SendFrom：_username:{0}",_username));
                        flg = tskTemp.SendFrom(_username, this._list_send.ToArray(), null, this._summary, ref incident, out error);
                        Logging.GetLogger().Error(string.Format("After tskTemp.SendFrom：_username:{0},incident:{1},error:{2}", _username,incident,error));
                        //if (flg)
                        {
                            _taskId = tskTemp.strTaskId;
                            _incident = incident;
                            //_is_allow_submit = false;
                        }
                        if (!string.IsNullOrEmpty(error))
                        {
                            throw new Exception("Send:" + error);
                        }
                    }
                    else
                    {
                        if (tskTemp.nTaskSubStatus == TaskSubStatuses.TASK_STATUS_ACTIVE_CONFERED)
                        {
                            flg = tskTemp.TakeBack(tskTemp.strUser);

                            if (flg)
                            {
                                incident = tskTemp.nIncidentNo;
                            }
                        }
                        else
                        {
                            flg = tskTemp.Send(_list_send.ToArray(), null, this._summary, ref incident, out error);

                            if (flg)
                            {
                                _incident = incident;
                                _is_allow_submit = false;
                            }

                            if (!string.IsNullOrEmpty(error))
                            {
                                throw new Exception("Send:" + error);
                            }
                        }
                    }
                }

                return incident != -2;

            }
            catch (Exception ex)
            {
                Logging.GetLogger().Error("方法 Send(提交表单步骤) 出错：" + ex);
                return false;
            }
        }
        #endregion

        #region 方法 DirectActive(激活步骤)
        /// <summary>
        /// 
        /// </summary>
        public bool DirectActive(string Step)
        {
            try
            {
                bool flg = false;
                Incident incTemp = new Incident();

                //根据 TaskID 去取得表单对应的 url 地址
                flg = incTemp.LoadIncident(_process, _incident);

                //如果返回为 true 时
                if (flg)
                {
                    //如果是"发起流程"的情况,由于流程尚未发起,异常;
                    if (IsInitiate)
                    {
                        throw new Exception("流程仍未发起的情况,不允许主动激活“" + Step + "”步骤!");
                    }
                    else
                    {
                        string strErr = "";
                        foreach (Variable var in _list_send)
                        {
                            if (var.objVariableValue == null)
                            {
                                continue;
                            }

                            if (var.objVariableValue.Length == 1)
                            {
                                incTemp.SetVariableValue(var.strVariableName, var.objVariableValue[0], out strErr);
                            }
                            else
                            {
                                incTemp.SetVariableValues(var.strVariableName, var.objVariableValue, out strErr);
                            }
                        }

                        if (_list_send.Count > 0)
                        {
                            flg = incTemp.SaveVariables();
                        }

                        flg = incTemp.DirectActivateStep(Step);
                    }
                }

                return flg;

            }
            catch (Exception)
            {
                return false;
            }
        }
        #endregion

        #region 方法 判断变量是否存在
        public bool IsVarExist(string VarName)
        {
            for (int i = 0; i < _list.Count; i++)
            {
                if (_list[i].strVariableName == VarName)
                {
                    return true;
                }
            }

            return false;
        }
        #endregion

        #region 索引 取得变量
        public object this[string VarName]
        {
            get
            {
                for (int i = 0; i < _list.Count; i++)
                {
                    if (_list[i].strVariableName == VarName)
                    {
                        return _list[i].objVariableValue == null ? new object[1] { "" } : _list[i].objVariableValue;
                    }
                }

                return new object[1] { "" };
            }
            set
            {
                object[] objValue = value != null && value.GetType().IsArray ? (object[])value : new object[1] { value == null ? "" : value };
                for (int j = 0; j < objValue.Length; j++)
                {
                    objValue[j] = objValue[j] == null ? "" : objValue[j];
                }

                bool flg = true;

                //同步原变量名列表
                for (int i = 0; i < _list.Count; i++)
                {
                    if (_list[i].strVariableName == VarName)
                    {
                        flg = false;
                        _list[i].objVariableValue = objValue;
                        break;
                    }
                }

                //如果电子表格里不存在指定的变量时,退出
                if (flg)
                {
                    return;
                }

                //表单提交临时值保存
                flg = true;
                for (int i = 0; i < _list_send.Count; i++)
                {
                    if (_list_send[i].strVariableName == VarName)
                    {
                        flg = false;

                        _list_send[i].objVariableValue = objValue;
                        break;
                    }
                }

                //如果不存在当前变量,追加
                if (flg)
                {
                    Variable o_tmp = new Variable();
                    o_tmp.strVariableName = VarName;
                    o_tmp.objVariableValue = objValue;
                    _list_send.Add(o_tmp);
                }
            }
        }
        #endregion

        #region 属性 Public
        /// <summary>
        /// TaskID
        /// </summary>
        public string TaskID
        {
            get { return _taskId; }
            set
            {
                _taskId = value;
            }
        }

        /// <summary>
        /// 流程名
        /// </summary>
        public string Process
        {
            get { return string.IsNullOrEmpty(_process) ? "" : _process; }
        }

        /// <summary>
        /// 实例号
        /// </summary>
        public int Incident
        {
            get { return _incident; }
        }

        public string ApplicationNo
        {
            get;
            set;
        }

        public string DraftID
        {
            get { return _DraftID; }
        }

        /// <summary>
        /// 步骤名
        /// </summary>
        public string Step
        {
            get { return _step == null ? "" : _step; }
        }

        /// <summary>
        /// 摘要
        /// </summary>
        public string Summary
        {
            get { return _summary == null ? "" : _summary; }
            set { _summary = value; }
        }

        /// <summary>
        /// 任务属主
        /// </summary>
        public string UserName
        {
            get { return _username; }
            set { _username = value; }
        }

        /// <summary>
        /// 任务属主
        /// </summary>
        public string UserFullName
        {
            get { return _userfullname; }
            set { _userfullname = value; }
        }

        /// <summary>
        /// 被指派人
        /// </summary>
        public string AssignedToUserName
        {
            get { return _assigned_to_username; }
            set { _assigned_to_username = value; }
        }

        /// <summary>
        /// 被指派人
        /// </summary>
        public string AssignedToUserFullName
        {
            get { return _assigned_to_userfullname; }
            set { _assigned_to_userfullname = value; }
        }

        public DateTime StartTime
        {
            get { return _starttime; }
        }

        /// <summary>
        /// 是否允许提交
        /// </summary>
        public bool IsAllowSubmit
        {
            get { return _is_allow_submit; }
            set { _is_allow_submit = value; }
        }

        /// <summary>
        ///  是否为发起步骤
        /// </summary>
        public bool IsInitiate
        {
            get { return _is_initiate; }
        }

        /// <summary>
        ///  是否为发起步骤
        /// </summary>
        public bool IsBeginStep
        {
            get { return _is_begin_step; }
        }

        /// <summary>
        ///  是否为指派
        /// </summary>
        public bool IsReAssigned
        {
            get { return _is_re_assigned; }
        }

        /// <summary>
        ///  是否为会办
        /// </summary>
        public bool IsConfered
        {
            get { return _is_confered; }
        }

        /// <summary>
        ///  是否加载
        /// </summary>
        public bool IsLoaded
        {
            get { return _loaded; }
        }

        #endregion
    }
    #endregion
}
